package org.example.studentteacherassignmentsystem.controller;

import org.example.studentteacherassignmentsystem.model.Student;
import org.example.studentteacherassignmentsystem.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import jakarta.validation.Valid;


@Controller
public class StudentController {
    @Autowired
    private StudentRepository studentRepository;

    @GetMapping("/newStudent")
    public String showStudentForm(Model model) {
        model.addAttribute("student", new Student());
        return "studentForm";
    }

    @PostMapping("/saveStudent")
    public String saveStudent(
            @Valid @ModelAttribute Student student,  // 触发验证
            BindingResult result,                    // 捕获验证错误
            Model model) {
        if (result.hasErrors()) {
            return "studentForm";
        }
        studentRepository.save(student);
        return "redirect:/";
    }
}